package com.example.myapplication

import android.annotation.TargetApi
import android.app.Activity
import android.os.Build
import android.os.Bundle
import android.view.Window
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.LinearLayout
import com.just.agentweb.AgentWeb
import com.just.agentweb.LogUtils
import ren.yale.android.cachewebviewlib.WebViewCacheInterceptor
import ren.yale.android.cachewebviewlib.WebViewCacheInterceptorInst
import ren.yale.android.cachewebviewlib.config.CacheExtensionConfig

class MainActivity : Activity() {

    private lateinit var meldsChangingLayout: LinearLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.activity_main)

        meldsChangingLayout = findViewById(R.id.web_layout)

        val builder = WebViewCacheInterceptor.Builder(this)
        val extension = CacheExtensionConfig()

        // 删除html类型的缓存
        extension.removeExtension("html")
        builder.setCacheExtensionConfig(extension)

        WebViewCacheInterceptorInst.getInstance().init(builder)

        val mAgentWeb = AgentWeb.with(this)
            .setAgentWebParent(meldsChangingLayout, LinearLayout.LayoutParams(-1, -1))
            .useDefaultIndicator() // 使用默认进度条
            .setWebViewClient(object : WebViewClient() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                override fun shouldInterceptRequest(
                    view: WebView,
                    request: WebResourceRequest
                ): WebResourceResponse? {
                    return WebViewCacheInterceptorInst.getInstance().interceptRequest(request)
                }

                override fun shouldInterceptRequest(
                    view: WebView,
                    url: String
                ): WebResourceResponse? {
                    return WebViewCacheInterceptorInst.getInstance().interceptRequest(url)
                }
            })
            .createAgentWeb()
            .ready()
            .go("file:///android_asset/CMNativeTest.html")
//            .go("http://192.168.50.178:8000/CMNativeTest.html?v="+ Calendar.getInstance().getTimeInMillis());
        try {
            val clazz: Class<*> = WebView::class.java
            val method =
                clazz.getMethod("setWebContentsDebuggingEnabled", Boolean::class.javaPrimitiveType)
            method.invoke(null, true)
        } catch (e: Throwable) {
            if (LogUtils.isDebug()) {
                e.printStackTrace()
            }
        }
        mAgentWeb.jsInterfaceHolder.addJavaObject(
            "CMNativeInterface",
            CMNativeInterface(mAgentWeb, this)
        )
    }
}